package org.lanqiao.controller;

import org.lanqiao.utils.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String path;


    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result<String> updateFile(MultipartFile file){

        //获取上传图片的文件名
        String fileName = file.getOriginalFilename();  //文件名+“.jpg""

        //截取”.jpg"后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));

        //生成的新图片名
        String newFileName = UUID.randomUUID().toString() + suffix;

        //创建一个目录对象，即配置文件中配置的目录
        File dir = new File(path);
        //判断配置文件中的路径是否存在
        if(!dir.exists()){
            //不存在则创建该目录
            dir.mkdirs();
        }

        try {
            //将上传的图片文件保存到定义的目录下
            file.transferTo(new File(path + newFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return Result.success(newFileName);
    }


    /**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void downFile(String name , HttpServletResponse response){

        try {
            //通过输入流读取文件
            FileInputStream inputStream = new FileInputStream(path + name);



            //通过输出流将读取到的图片文件显示在浏览器中
            ServletOutputStream outputStream = response.getOutputStream();

            //设置响应的文件类型为图片
            response.setContentType("image/jpeg");

            int len = 0;
            byte[] bytes = new byte[1024];
            while((len = inputStream.read(bytes)) != -1){
                outputStream.write(bytes , 0 , len);
                outputStream.flush();
            }

            inputStream.close();
            outputStream.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
